package com.heima.search.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    //索引库名
    public static final String APP_INFO_ARTICLE = "app_info_article";

    //读取前缀
    @Value("${file.minio.readPath}")
    String readPath;

    @Autowired
    EsService<SearchArticleVO> esService;

    @Autowired
    ApUserSearchService apUserSearchService;

    /**
     * 文章搜索
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDTO dto) {

        dto.setMinBehotTime(new Date());
        //1 参数检查
        String searchWords = dto.getSearchWords();
        if (StringUtils.isBlank(searchWords)||searchWords==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数无效");
        }
        //=========================  记录搜索历史记录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user !=null){
            dto.setEntryId(user.getId());
        }
        //========异步调用保存用户输入的关键词记录
        apUserSearchService.insert(dto);
        //=========================================================
        //2 构建查询条件执行查询
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 构建查询条件和过滤等 布尔查询组合查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 关键词查询
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", searchWords);

        //绑定条件
        boolQueryBuilder.must(matchQuery);
        // 查询小于mindate的数据
        RangeQueryBuilder builder = QueryBuilders.rangeQuery("publishTime")
                                                 .lt(dto.getMinBehotTime().getTime());
        boolQueryBuilder.filter(builder);
        // 分页
        sourceBuilder.from(0);
        sourceBuilder.size(dto.getPageSize());
        // 按照发布时间倒序
        sourceBuilder.sort("publishTime", SortOrder.DESC);
        // 高亮 三要素
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title"); //搜索时标题高亮显示
        //格式
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");

        //绑定查询条件
        sourceBuilder.highlighter(highlightBuilder);
        //绑定组合查询 boolQuery
        sourceBuilder.query(boolQueryBuilder);

        //调用service进行分页查询 得到结果
        PageResponseResult result = esService.search(sourceBuilder, SearchArticleVO.class, APP_INFO_ARTICLE);
        //从结果中拿出集合数据
        List<SearchArticleVO> searchArticleVOList = (List<SearchArticleVO>) result.getData();

        //判断集合是否为空
        if (CollectionUtils.isNotEmpty(searchArticleVOList)) {
            //不为空,遍历集合,staticUrl 需要拼接 minIO文章服务器的前缀路径
            for (SearchArticleVO searchArticleVO : searchArticleVOList) {
                searchArticleVO.setStaticUrl(readPath+searchArticleVO.getStaticUrl());
            }
        }
        //4 返回结果
        return result;
    }

    /**
     * 文章上架或发布时保存文章到es索引库
     * @param article
     */
    @Override
    public void saveArticle(SearchArticleVO article) {
        //调用esService 的 save方法 保存文章
        esService.save(article,APP_INFO_ARTICLE);
    }

    /**
     * 文章下架或删除时,从es索引库中删除文章
     * @param articleId
     */
    @Override
    public void deleteArticle(String articleId) {
        //调用esService 的 deleteById方法,删除文章
        esService.deleteById(articleId,APP_INFO_ARTICLE);
    }
}